<?php

namespace app\base\controller\miniapp\member;

use app\base\model\CouponModel;

use app\base\model\logs\MemberBalanceLogsModel;

use app\base\model\logs\MemberIntegralLogsModel;

use app\base\model\member\MemberBalanceModel;

use app\base\model\member\MemberCouponModel;

use app\base\model\member\MemberIntegralModel;

use app\base\model\order\BuyOrderModel;

use app\base\model\setting\SettingBalanceModel;

use app\base\model\StaffModel;

use app\BaseController;

use app\common\logic\TokenLogic;



class Member extends BaseController{

    public function show()

    {

        $member=$this->request->member;

        $member->append(['hidden_mobile','birthday']);

        $balance = MemberBalanceModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member->member_id],

                ['valid_bg_time','<=',$this->request->time()]

            ])->sum('remain_balance') ?? 0;

        $frozen_balance=MemberBalanceModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member->member_id],

                ['valid_bg_time','>',$this->request->time()]

            ])->sum('remain_balance') ?? 0;;





        $integral = MemberIntegralModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member->member_id],

                ['expire_time','>',$this->request->time()]

            ])->sum('remain_integral') ?? 0;



        $coupon_count = MemberCouponModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member->member_id],

            ])->count() ?? 0;

        

        $shopStaff = StaffModel::where([

            ['shop_id','=',$this->request->shopId],

            ['mobile','=',$member->mobile],

            ['status','=',1],

            ['is_delete','=',0]

        ])->find();



        $is_staff = $shopStaff===null ? 0 : 1;



        $return=[

            'member_info'=>[

                'member_id' => $member->member_id,

                'nick_name'=>$member->nick_name,

                'birthday' => $member->birthday, 

                'sex'       => $member->sex,

                'face'=>$member->face,

                'level_id'=>$member->level_id,

                'level_name'=>$member->level ? $member->level->name : '普通会员',

                'balance'=>$balance,

                'frozen_balance'=>$frozen_balance,

                'total_balance' =>round(($balance *  100  + $frozen_balance * 100)/100,2),

                'integral'=>$integral,

                'coupon_count'=>$coupon_count,

                'hidden_mobile'=>$member->hidden_mobile,

                'is_staff'=>$is_staff

            ]

        ];

        return $this->success($return);

    }



    //获取用户的Qrcode

    public function getMemberQrcode(){

        $member = $this->request->member;

        $code=rand(111111,999999);

        $member->code=$code;

        $member->save();

        return $this->success([

            'member_id'=>$member->member_id,

            'code'=>$code

        ]);

    }



    public function saveMemberInfo()

    {

        $nick_name = $this->request->param('nick_name');

        $sex = $this->request->param('sex/d',0);

        $birthday = $this->request->param('birthday');

        $face = $this->request->param('face');



        if(empty($nick_name) || mb_strlen($nick_name) >32) return $this->error('请输入昵称且昵称长度不能多余32');

        if(!in_array($sex,[0,1,2])) return $this->error('请选择性别');

        if(empty($birthday)) return $this->error('请选择生日');

        if(false === strtotime($birthday." 00:00:00")) return $this->error('请选择正确的生日');

        $birthday_arr=explode('-',$birthday);

        if(count($birthday_arr) !=3) return $this->error('请选择正确的生日');

        $birthday_year=$birthday_arr[0]; $birthday_month=$birthday_arr[1]; $birthday_day=$birthday_arr[2];

//        if((mb_strlen($birthday_year) !=4) || (mb_strlen($birthday_month) !=2) (mb_strlen($birthday_day) !=2)) return $this->error('请选择正确的生日');



        $member=$this->request->member;

        $member->nick_name=$nick_name;

        if(!empty($face)){

            $member->face = $face;

        }

        $member->sex=$sex;

        $member->birthday_year=$birthday_year;

        $member->birthday_month=$birthday_month;

        $member->birthday_day=$birthday_day;

        $member->save();



        return $this->success("修改成功");

    }





    public function getMemberBalanceLogs()

    {

        



        $datas=MemberBalanceLogsModel::where([

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$this->request->memberId],

        ])->field('type,info,balance,give_balance,add_time')

            ->order(['add_time'=>'desc'])

            ->limit($this->request->limit)

            ->page($this->request->page)

            ->select()->append(['add_time_format'])

            ->toArray();

        $return['datas']=$datas;

        if($this->request->page == 1){

            $setting_balance = SettingBalanceModel::where([['shop_id','=',$this->request->shopId]])->find();

            if(null !== $setting_balance){

                $return['setting_balance']=[

                    'is_frozen_give_money'=>$setting_balance->is_frozen_give_money,

                    'frozen_days'=>$setting_balance->frozen_days,

                    'can_recharge'=>empty($setting_balance->taocan_detail) ? 0 : 1,

                ];

            }

        }

        return $this->success($return);

    }



    //获取充值套餐

    public function getBalancePackage(){

        $setting_balance = SettingBalanceModel::where([['shop_id','=',$this->request->shopId]])->find();



        if(null === $setting_balance) return $this->error('充值配置未设置，无法充值');

        if(empty($setting_balance->taocan_detail)) return $this->error('充值套餐未设置，无法充值');



        $datas=$setting_balance->taocan_detail;

        $coupon_ids='';

        foreach ($datas as $val){

            if(!empty($val['coupon'])){

                $coupon_ids=$coupon_ids.','.implode(',',$val['coupon']);

            }

        }

        $coupon_ids=explode(',',$coupon_ids);

        $today = date('Y-m-d', $this->request->time());

        $coupons=CouponModel::where([

            ['coupon_id','in',$coupon_ids],

            ['shop_id','=',$this->request->shopId],

            ['valid_end_time','>=',$today],

        ])->field('coupon_id,name')->select()->toArray();



        $coupon_id=array_column($coupons,'coupon_id');

        foreach ($datas as $key=>$val){

            $coupon_name=[];

            if(!empty($val['coupon'])){

                foreach ($val['coupon'] as $k=>$v){

                    $index = array_search($v, $coupon_id);

                    $coupon_name[]=$coupons[$index]['name'];

                }

            }

            $datas[$key]['coupon_money']=implode('、',$coupon_name);

        }



        return $this->success(['datas'=>$datas]);

    }



    //获取我的积分明细

    public function getMemberIntegralLogs()

    {



        $datas=MemberIntegralLogsModel::where([

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$this->request->memberId],

        ])->field('type,info,integral,add_time')

            ->order(['add_time'=>'desc'])

            ->limit($this->request->limit)

            ->page($this->request->page)

            ->select()->append(['add_time_format'])

            ->toArray();

        $return['datas']=$datas;



        return $this->success($return);

    }



    public function getMemberBuyLogs()

    {

        $datas=BuyOrderModel::where([

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$this->request->memberId],

            ['is_paid','=',1]

        ])->field('balance,vip_balance,coupon_money,integral_balance,add_time')

            ->order(['add_time'=>'desc'])

            ->limit($this->request->limit)

            ->page($this->request->page)

            ->select()->append(['add_time_format','price','discount_money'])

            ->toArray();

        $return['datas']=$datas;



        return $this->success($return);

    }

}

